package net.jiastudy.core.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

import net.jiastudy.core.exception.ServiceException;

public class BeanUtils extends org.springframework.beans.BeanUtils {

	public static void copyPropertiesWithIgnoreProperties(Object source, Object target, String... ignoreProperties)
			throws BeansException {
		copyProperties(source, target, ignoreProperties);
	}

	public static void copyPropertiesWithCopyProperties(Object source, Object target, String... copyProperties)
			throws BeansException {

		Assert.notNull(source, "Source must not be null");
		Assert.notNull(target, "Target must not be null");

		Class<?> actualEditable = target.getClass();

		PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
		List<String> copyList = (copyProperties != null ? Arrays.asList(copyProperties) : null);

		for (PropertyDescriptor targetPd : targetPds) {
			Method writeMethod = targetPd.getWriteMethod();
			if (writeMethod != null && (copyList == null || copyList.contains(targetPd.getName()))) {
				PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
				if (sourcePd != null) {
					Method readMethod = sourcePd.getReadMethod();
					if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0],
							readMethod.getReturnType())) {
						try {
							if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
								readMethod.setAccessible(true);
							}
							Object value = readMethod.invoke(source);
							if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
								writeMethod.setAccessible(true);
							}
							writeMethod.invoke(target, value);
						} catch (Throwable ex) {
							throw new FatalBeanException(
									"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
						}
					}
				}
			}
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Method getGetMethod(Class objectClass, String fieldName) {
		StringBuffer sb = new StringBuffer();
		sb.append("get");
		sb.append(fieldName.substring(0, 1).toUpperCase());
		sb.append(fieldName.substring(1));
		try {
			return objectClass.getMethod(sb.toString());
		} catch (Exception e) {
			throw new ServiceException("500", e.getMessage());
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Method getSetMethod(Class objectClass, String fieldName) {
		try {
			Class[] parameterTypes = new Class[1];
			Field field = objectClass.getDeclaredField(fieldName);
			parameterTypes[0] = field.getType();
			StringBuffer sb = new StringBuffer();
			sb.append("set");
			sb.append(fieldName.substring(0, 1).toUpperCase());
			sb.append(fieldName.substring(1));
			Method method = objectClass.getMethod(sb.toString(), parameterTypes);
			return method;
		} catch (Exception e) {
			throw new ServiceException("500", e.getMessage());
		}
	}

	public static Set<?> getFiled(List<?> entitys, String fieldName) {
		if (null == entitys) {
			return null;
		}
		Set<Object> set = new HashSet<>();
		try {
			for (Object entity : entitys) {
				Class<? extends Object> clazz = entity.getClass();
				Method m = getGetMethod(clazz, fieldName);
				Object value = m.invoke(entity);
				if (null != value) {
					set.add(value);
				}
			}
		} catch (Exception e) {
			throw new ServiceException("500", e.getMessage());
		}
		return set;
	}

	@SuppressWarnings("unchecked")
	public static <T> Set<T> getFiled(List<?> entitys, String fieldName, Class<T> returnClazz) {
		if (null == entitys) {
			return null;
		}
		Set<T> set = new HashSet<>();
		try {
			for (Object entity : entitys) {
				Class<? extends Object> clazz = entity.getClass();
				Method m = getGetMethod(clazz, fieldName);

				T value = (T) m.invoke(entity);
				if (null != value) {
					set.add(value);
				}
			}
		} catch (Exception e) {
			throw new ServiceException("500", e);
		}
		return set;
	}

	public static Map<?, ?> toMap(List<?> entitys, String fieldName) {
		if (null == entitys) {
			return null;
		}
		Map<Object, Object> map = new HashMap<>();
		try {
			for (Object entity : entitys) {
				Class<? extends Object> clazz = entity.getClass();
				Method m = getGetMethod(clazz, fieldName);
				map.put(m.invoke(entity), entity);
			}
		} catch (Exception e) {
			throw new ServiceException("500", e.getMessage());
		}
		return map;
	}
}
